package gamesys.games.particlesystem.graphics
{
	import gamesys.games.particlesystem.utils.BitmapUtils;

	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	import flash.utils.getDefinitionByName;

	/**
	 * @author robertthurston
	 */
	public class BitmapAnimationFactory
	{
		private static var INSTANCE : BitmapAnimationFactory;
		private var _animations : Dictionary;

		public function BitmapAnimationFactory(singletonForcer : SingletonForcer)
		{
			_animations = new Dictionary();
		}

		public static function getInstance() : BitmapAnimationFactory
		{
			return (INSTANCE) ? INSTANCE : new BitmapAnimationFactory(new SingletonForcer());
		}

		public function getBitmapAnimation(linkage : String) : BitmapAnimation
		{
			var bitmapAnimation : BitmapAnimation;

			if (_animations[linkage])
			{
				bitmapAnimation = _animations[linkage];
			}
			else
			{
				bitmapAnimation = createAnimation(linkage);
				_animations[linkage] = bitmapAnimation;
			}

			return bitmapAnimation;
		}

		public function getMultipleBitmapAnimations(linkages : Array) : Array
		{
			var array : Array = new Array();

			for (var i : int = 0;i < linkages.length;i++)
			{
				array.push(getBitmapAnimation(linkages[i]));
			}

			return array;
		}

		private function createAnimation(linkage : String) : BitmapAnimation
		{
			var source : MovieClip = new (getDefinitionByName(linkage))() as MovieClip;
			var bounds : Rectangle = BitmapUtils.getAccumulatedBounds(source);
			var bitmapAnimation : BitmapAnimation = new BitmapAnimation(buildAnimation(source, bounds));

			bitmapAnimation.x = bounds.x;
			bitmapAnimation.y = bounds.y;
			bitmapAnimation.width = bounds.width;
			bitmapAnimation.height = bounds.height;

			return bitmapAnimation;
		}

		private function buildAnimation(source : MovieClip, bounds : Rectangle) : Array
		{
			var animation : Array = new Array;

			for (var frame : int = 1; frame <= source.totalFrames; frame++)
			{
				var bitmapData : BitmapData = BitmapUtils.getBitmapDataFromMovieClip(source, frame, bounds);
				animation.push(bitmapData);
			}

			return animation;
		}
	}
}
class SingletonForcer
{
}
